package com.sjgame.base.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sjgame.base.common.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * create by zcl
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = {"/login"}, method = RequestMethod.POST)
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        ModelMap model) {
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            return redirect("/index");
        } catch (AuthenticationException e) {
            model.put("message", e.getMessage());
        }
        return "login";
    }

    @RequestMapping(value = {"/logout"}, method = RequestMethod.GET)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return redirect("login");
    }

    @RequestMapping(value = {"/checkcode"}, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult checkCode(String code, ModelMap modelMap) {

        try {

            Subject subject = SecurityUtils.getSubject();
            subject.getSession().getAttribute("KAPTCHA_SESSION_KEY");
            if (code == null ||subject.getSession().getAttribute("KAPTCHA_SESSION_KEY") /*request.getSession().getAttribute("KAPTCHA_SESSION_KEY")*/ == null) {
                return JsonResult.failure("请输入验证码");
            }
            if (!code.equals(subject.getSession().getAttribute("KAPTCHA_SESSION_KEY")/*request.getSession().getAttribute("KAPTCHA_SESSION_KEY")*/)) {
                return JsonResult.failure("验证码无效");

            }

        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }


    @RequestMapping("/Kaptcha.jpg")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
         //   httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", createText);
            Subject subject = SecurityUtils.getSubject();
            subject.getSession().setAttribute("KAPTCHA_SESSION_KEY", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

}
